package com.tf8.treasure.interceptor;

import com.tf8.treasure.domain.ResponseInfo;
import com.tf8.treasure.enums.ReturnType;
import com.tf8.treasure.exception.RequestException;
import com.tf8.treasure.utils.ITools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ControllerAdvice;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@ControllerAdvice
@ResponseBody
public class ExceptionHandlerAdvice {

    @ExceptionHandler(RequestException.class)
    public ResponseEntity sessionNotFoundExceptionHandler(HttpServletRequest request, RequestException exception) throws Exception {
        log.info(exception.getMessage());
        exception.setErrorCode(ITools.getDefaultIfBlank(exception.getErrorCode(), ReturnType.ERROR.getCode()));
        return ResponseEntity.ok(new ResponseInfo<>(exception.getErrorCode(),exception.getMessage()));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity handleException(Exception exception, HttpServletRequest request) {
        if(!(exception instanceof HttpRequestMethodNotSupportedException))
            log.error(exception.getMessage(),exception);
        return ResponseEntity.ok(new ResponseInfo<>(ReturnType.ERROR.getCode(),ReturnType.ERROR.getMsg()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity handleIllegalParamException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message="";
        for (FieldError error: bindingResult.getFieldErrors()) {
            message += error.getField()+" : "+error.getDefaultMessage() +";";
        }
        log.error(message);
        return ResponseEntity.ok(new ResponseInfo(ReturnType.PARAM_ERROR.getCode(),message));
    }
 
}
